<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :width="width" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" class="menuForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { inputFormSchemas } from "./data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { listLogTypeTree, saveOrUpdateLogType } from "./api"
  import { useAdapt } from "/@/hooks/system/useAutoAdapt"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()
  const emit = defineEmits(["success", "register"])
  const { width } = useAdapt({ xl: 600, lg: 600, md: 600, sm: 600, xs: 600 })
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const parentId = ref("0")

  const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate, getFieldsValue }] = useForm({
    labelWidth: 80,
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 20 },
    },
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate
      parentId.value = data?.record?.parentId
      const treeData = await listLogTypeTree({ })
      console.log('treeData', treeData)
      updateSchema([
        {
          field: "parentId",
          componentProps: {
            showSearch: true,
            treeData: treeData,
            fieldNames: {
              title: "name",
              key: "id",
              value: "id",
              pid: 'parentId'
            },
          }
        }
      ])

      if (typeof data.record === "object") {
        let values = { ...data.record }
        setFieldsValue(values)
      }
    } finally {
      setDrawerProps({ confirmLoading: false, loading: false })
    }
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增日志类型" : "编辑日志类型"))

  async function handleSubmit() {
    try {
      const values = await validate()
      console.log("submit menu: ", values)

      if (isUpdate.value && values.parentId == values.id) {
        createMessage.error("上级不能选择自己")
        return
      }

      setDrawerProps({ confirmLoading: true })
      await saveOrUpdateLogType({ ...values }, unref(isUpdate))
      closeDrawer()
      createMessage.success(`${getTitle.value}成功`)
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
